package com.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录验证
 */
@Slf4j
@RestController
public class HelloController {

    @RequestMapping("login")
    public Object login(String username, String password) {
        // 添加用户认证信息
        Subject subject = SecurityUtils.getSubject();

        // 是否已登陆
        if (subject.isAuthenticated()) {
            log.info("已登陆");
        }

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        // 记住我
        usernamePasswordToken.setRememberMe(true);

        // 进行验证，可以捕获异常，然后返回对应信息
        subject.login(usernamePasswordToken);
        // subject.checkRole("admin");
        // subject.checkPermissions("query", "add");

        return "login success";
    }

    // 注解验证角色和权限
    @RequiresRoles("admin")
    @RequiresPermissions("add")
    @RequestMapping("/index")
    public Object index() {
        return "index";
    }

    @RequestMapping(value = "logout")
    public Object logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "logout success";
    }
}
